package com.hello.pet.service.system.utils;

import cn.hutool.core.io.FileTypeUtil;
import com.hello.pet.common.exception.BaseException;
import org.springframework.web.multipart.MultipartFile;

import java.io.IOException;
import java.util.Arrays;
import java.util.List;

public class FileUtils {

    /**
     * 图片类型
     */
    public static List<String> fileType = Arrays.asList("BMP", "JPG", "PNG", "TIF", "GIF", "PCX", "TGA", "EXIF", "FPX", "SVG",
            "PSD", "CDR", "PCD", "DXF", "UFO", "EPS", "AI", "RAW", "WMF", "WEBP", "AVIF", "APNG");

    /**
     * 检查文件大小限制
     *
     * @param len
     * @param size
     * @param unit
     */
    public static void checkFileSize(Long len, int size, String unit) {
        double fileSize = 0;
        if ("B".equals(unit.toUpperCase())) {
            fileSize = (double) len;
        } else if ("K".equals(unit.toUpperCase())) {
            fileSize = (double) len / 1024;
        } else if ("M".equals(unit.toUpperCase())) {
            fileSize = (double) len / 1048576;
        } else if ("G".equals(unit.toUpperCase())) {
            fileSize = (double) len / 1073741824;
        }
        if (fileSize > size) {
            throw new BaseException("文件大小超过限制!");
        }
    }

    /**
     * 判断文件类型
     *
     * @param file
     */
    public static void checkFileType(MultipartFile file) {
        try {
            String type = FileTypeUtil.getType(file.getInputStream(), file.getOriginalFilename());
            if (fileType.stream().noneMatch(it -> it.equals(type.toUpperCase())))
                throw new BaseException("仅支持文件类型为:" + fileType.toString());
        } catch (IOException ex) {
            throw new BaseException("文件类型解析异常",ex);
        }
    }
}